/*
 * Copyright @ 2018 河南雪城软件有限公司  All rights reserved.
 *
 */

package com.hw.one.peach.da.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hw.one.client.Client;
import com.hw.one.component.data.transform.excel.Export;
import com.hw.one.core.controller.BaseController;
import com.hw.one.core.logger.annotation.SystemLog;
import com.hw.one.core.logger.constant.LogConstants;
import com.hw.one.core.result.MsgResult;
import com.hw.one.core.service.IDictionaryService;
import com.hw.one.peach.da.service.IPeachAirService;
import com.hw.one.peach.da.service.IPeachDeviceService;

import io.swagger.annotations.ApiOperation;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.util.WebUtils;

/**
 * <p>
 * 详细描述
 * </p>
 *
 * @author Erick
 * @date 2018/4/17
 */
@RestController
@RequestMapping("air")
public class AirController extends BaseController {

	@Resource
	private IPeachDeviceService peachDeviceService;

	@Resource
	private IDictionaryService dictionaryService;

	@Resource
	private IPeachAirService peachAirService;
	
	/**
	 * 获取大气六因子列表
	 * @return List<map> 站点名/code 设备名/code 文件名 文件大小 文件创建时间
	 */
	@ApiOperation(value = "大气六因子", notes = "获取大气六因子列表", httpMethod = "GET")
	@SystemLog(moduleName = "大气六因子", description = "获取大气六因子列表", operType = LogConstants.OPER_SELECT)
	@Override
	public MsgResult get(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'AIR'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			
			Client c = Client.getInstance();
			String ret = c.execute("air-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);
			
			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("无参查询异常", e);
		}
		return result;
	}
	
	/**
	 * 下载大气六因子数据
	 * @return List<map> 站点名/code 设备名/code 文件名 文件大小 文件创建时间
	 */
	@ApiOperation(value = "大气六因子", notes = "下载大气六因子数据", httpMethod = "GET")
	@SystemLog(moduleName = "大气六因子", description = "下载大气六因子数据", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "download", method = RequestMethod.GET)
	public void download(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> params = wrapParams(request);
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'AIR'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			
			Client c = Client.getInstance();
			String result1 = c.execute("air-original-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);
			MsgResult obj = JSON.parseObject(result1, MsgResult.class);
			Gson gson = new Gson();
			JSONObject o = (JSONObject) JSON.toJSON(obj.getData());
			List<Map<String,String>> list = gson.fromJson(o.get("rows").toString(), new TypeToken<List<HashMap<String, String>>>() {}.getType());
			
			Map<String, Object> exceldata = new HashMap<String, Object>();
			exceldata.put("air", list);
			
			Map<String, Object> sheet = new HashMap<String, Object>();
			sheet.put("Sheet1", exceldata);
			
			Export export = new Export();
			String dataType = String.valueOf(params.get("dataType"));
			String template = "";
			if (dataType.equals("hourData")) {
				template = "ext/tpl/excel/da/tpl-air-hour-export.xml";
			} else {
				template = "ext/tpl/excel/da/tpl-air-day-export.xml";
			}
			InputStream xml = this.getClass().getClassLoader().getResourceAsStream(template);
			Workbook workbook = export.exportExcelFromData(xml, sheet);
			
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("空气六因子数据.xlsx".getBytes("UTF-8"), "ISO-8859-1"));
			response.setContentType("multipart/form-data");
			
//			OutputStream out = new FileOutputStream(new File("E:\\空气六因子数据.xlsx"));
//			workbook.write(out);
//			out.flush();
//			out.close();
			OutputStream os = response.getOutputStream();
			workbook.write(os);
			os.flush();
			os.close();
		} catch (Exception e) {
			log.error("无参查询异常", e);
		}
	}
	
	/**
	 * 获取大气六因子及气象五参下拉框数据
	 * @return 
	 */
	@ApiOperation(value = "大气六因子", notes = "获取大气六因子列表", httpMethod = "GET")
	@SystemLog(moduleName = "大气六因子", description = "获取大气六因子列表", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "combo", method = RequestMethod.GET)
	public MsgResult combo(HttpServletRequest request) {
		MsgResult result = null;
		try {
			JSONArray arr = new JSONArray();
			JSONObject obj = new JSONObject();
			JSONObject ret = new JSONObject();
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("code", "meteorology");
			List<Map<String, Object>> meteorology = dictionaryService.retrieveChildListByCode(params);
			
			for (Map<String, Object> map : meteorology) {
				obj = new JSONObject();
				obj.put("value", map.get("code"));
				obj.put("label", map.get("display"));
				
				arr.add(obj);
			}
			ret.put("meteorology", arr);
			
			params.put("code", "air");
			List<Map<String, Object>> air = dictionaryService.retrieveChildListByCode(params);
			arr = new JSONArray();
			for (Map<String, Object> map : air) {
				obj = new JSONObject();
				obj.put("value", map.get("code"));
				obj.put("label", map.get("display"));
				
				arr.add(obj);
			}
			ret.put("air", arr);
			result = MsgResult.okResult(ret);
		} catch (Exception e) {
			log.error("无参查询异常", e);
		}
		return result;
	}
	
	/**
	 * <p>
	 * 导入大气六因子数据
	 * <p>
	 * 
	 * @return MsgResult 
	 * @author zhangshaowei
	 * @create 2018年07月16日下午3:38:28
	 */
	@ApiOperation(value = "air", notes = "导入大气六因子数据", httpMethod = "POST")
	@SystemLog(moduleName = "air", description = "导入大气六因子数据", operType = LogConstants.OPER_ADD)
	@RequestMapping(path = "upload", method = RequestMethod.POST)
	public MsgResult upload(HttpServletRequest request) {
		Map<String, Object> params = wrapParams(request);
		try {
			MultipartHttpServletRequest multipartRequest = WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
			Map<String, MultipartFile> files = multipartRequest.getFileMap();

			peachAirService.upload(params, files);

			return MsgResult.okResult();
		} catch (Exception e) {
			log.error("导入vocs定量报告异常", e);
			return MsgResult.exceptionResult(e.getMessage());
		}
	}
	
	/**
	 * 机房数据
	 * 机房室内温湿度
	 * @return
	 */
	@ApiOperation(value = "机房数据", notes = "机房室内温湿度", httpMethod = "GET")
	@SystemLog(moduleName = "机房数据", description = "机房室内温湿度", operType = LogConstants.OPER_SELECT)
	@RequestMapping(path = "indoor-data", method = RequestMethod.GET)
	public MsgResult findDeviceData(HttpServletRequest request, HttpServletResponse response) {
		Map<String, Object> params = wrapParams(request);
		MsgResult result = null;
		try {
			// 站点code和设备类型取设备code
			params.put("monitorCode", "'AIR'");
			List<Map<String, Object>> devices = peachDeviceService.getDeviceBySite(params);
			params.put("deviceCode", devices.get(0).get("SNCODE"));
			
			Client c = Client.getInstance();
			String ret = c.execute("air-indoor-data", params, new HashMap<String, Object>(), com.hw.one.client.RequestMethod.GET);
			
			if (ret == null) {
				result = MsgResult.okResult();
			} else {
				result = JSONObject.parseObject(ret, MsgResult.class);
			}
		} catch (Exception e) {
			log.error("无参查询异常", e);
		}
		return result;
	}
}
